package com.tool.app.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;
import java.util.TimeZone;

public class WebJsonConverterConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 1. 创建一个统一的 ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();

        // 2. 注册 Long 序列化器（避免 "123456789" → 1.23456789E8）
        SimpleModule longModule = new SimpleModule();
        longModule.addSerializer(Long.class, ToStringSerializer.instance);
        longModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(longModule);

        // 3. 注册 Date 反序列化器
        SimpleModule dateModule = new SimpleModule();
        dateModule.addDeserializer(java.sql.Date.class, new SqlDateUtcDeserializer());
        objectMapper.registerModule(dateModule);

        // 4. 设置时区为 UTC
        //objectMapper.setTimeZone(TimeZone.getTimeZone("UTC"));

        // 5. 关闭未知属性报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 6. 创建转换器并插入最前面
        MappingJackson2HttpMessageConverter converter =
            new MappingJackson2HttpMessageConverter(objectMapper);
        
        // ✅ 插入最前面，优先级最高
        converters.add(0, converter);
    }
}